package com.cargohu.aishouyu.member.service.impl;

import com.cargohu.aishouyu.framework.exception.BusinessException;
import com.cargohu.aishouyu.framework.page.OrderByItem;
import com.cargohu.aishouyu.framework.page.Paging;
import com.cargohu.aishouyu.framework.service.impl.BaseServiceImpl;
import com.cargohu.aishouyu.member.dto.MemberAddDTO;
import com.cargohu.aishouyu.member.dto.MemberUpdateDTO;
import com.cargohu.aishouyu.member.entity.Member;
import com.cargohu.aishouyu.member.mapper.MemberMapper;
import com.cargohu.aishouyu.member.req.MemberRequest;
import com.cargohu.aishouyu.member.resp.MemberDetailVo;
import com.cargohu.aishouyu.member.resp.MemberResponse;
import com.cargohu.aishouyu.member.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 会员表 服务实现类
 *
 * @author aaron.wang
 * @since 2023-11-27
 */
@Slf4j
@Service
public class MemberServiceImpl extends BaseServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addMember(MemberAddDTO memberAddDTO) throws Exception {
        Member member = new Member();
        BeanUtils.copyProperties(memberAddDTO, member);
        return save(member);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateMember(MemberUpdateDTO memberUpdateDTO) throws Exception {
        Long memberId = memberUpdateDTO.getMemberId();
        Member member = getById(memberId);
        if (member == null) {
            throw new BusinessException("会员信息不存在");
        }
        BeanUtils.copyProperties(memberUpdateDTO, member);
        member.setUpdateTime(new Date());
        return updateById(member);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteMember(Long memberId) throws Exception {
        return removeById(memberId);
    }

    @Override
    public MemberDetailVo getMemberById(Long memberId) throws Exception {
        return memberMapper.getMemberById(memberId);
    }

    @Override
    public Paging<MemberResponse> getMemberList(MemberRequest memberRequest) throws Exception {
        handlePage(memberRequest, OrderByItem.desc("member_id"));
        List<MemberResponse> list = memberMapper.getMemberList(memberRequest);
        Paging<MemberResponse> paging = new Paging<>(list);
        return paging;
    }

}
